package com.ymnet.myretrofit;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by MajinBuu on 2018/1/4 0004.
 *
 * @overView ${todo}.
 */

public class RetrofitClient {

    private static RetrofitClient sRetrofit;
    private String BASE_URL = "https://api.github.com/";
    private static Context sContext;
    private static final int HTTP_RESPONSE_DISK_CACHE_MAX_SIZE = 10 * 1024 * 1024;

    public static RetrofitClient getInstance(Context context) {
        if (sRetrofit == null) {
            sContext = context;
            sRetrofit = new RetrofitClient();
        }
        return sRetrofit;
    }

    public GitHubService builder() {
        return getGitHubService(BASE_URL);
    }

    public GitHubService builder(String baseUrl) {
        return getGitHubService(baseUrl);
    }

    private GitHubService getGitHubService(String baseUrl) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(addLogInterceptor())
                .retryOnConnectionFailure(true)
                .connectTimeout(3000, TimeUnit.MILLISECONDS)//连接超时设置为3000ms
                .readTimeout(3000, TimeUnit.MILLISECONDS)
                .writeTimeout(3000, TimeUnit.MILLISECONDS)
                //设置Cache目录
//                  .cache(getCache())
                //设置缓存
                //  .addInterceptor(addCacheInterceptor())
                //  .addNetworkInterceptor(addCacheInterceptor())
                .build();
        GitHubService gitHubService = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(GitHubService.class);
        return gitHubService;
    }

    /**
     * 或者提取请求框架,并在callback回调中做判断 ${@link CacheManager}
     * CacheManager.getInstance().saveCache();
     * CacheManager.getInstance(sContext).getCacheString()
     * @return
     */
    private Cache getCache() {
        return new Cache(new File(sContext.getExternalCacheDir(), "cache_file"), HTTP_RESPONSE_DISK_CACHE_MAX_SIZE);
    }

    /**
     * 类似link http://blog.csdn.net/changsimeng/article/details/54668884
     * @return
     */
    private Interceptor addCacheInterceptor() {
        Interceptor interceptor = new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();

                if (!NetUtil.isNetworkAvailable(sContext)) {
                    request = request.newBuilder()
                            //强制使用缓存
                            .cacheControl(CacheControl.FORCE_CACHE).build();
                }

                Response response = chain.proceed(request);

                if (NetUtil.isNetworkAvailable(sContext)) {
                    //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
                    String cacheControl = request.cacheControl().toString();
                    return response.newBuilder()
                            .header("Cache-Control", cacheControl)
                            .removeHeader("Pragma")//移除干扰信息
                            .build();
                } else {
                    int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
                    return response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                            .removeHeader("Pragma")
                            .build();
                }
            }
        };

        return interceptor;
    }

    private Interceptor addLogInterceptor() {
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Buffer requestBuffer = new Buffer();
                if (request.body() != null) {
                    request.body().writeTo(requestBuffer);
                } else {
                    Log.i("LogTAG", "request.body() == null");
                }
                Log.e("requestUrl", request.url() + (request.body() != null ? "?" + parseParams(request.body(), requestBuffer) : ""));
                Response response = chain.proceed(request);
                return response;
            }
        };
        return interceptor;
    }

    private String parseParams(RequestBody body, Buffer requestBuffer) throws UnsupportedEncodingException {
        if (body.contentType() != null && !body.contentType().toString().contains("multipart")) {
            return URLDecoder.decode(requestBuffer.readUtf8(), "UTF-8");
        }
        return "null";
    }


}
